<template>
    <div class="flex">
        <el-button @click="save">保存</el-button>
        <el-upload ref="uploadRef" class="upload-demo" :on-change="handleImport" :auto-upload="false">
            <template #trigger>
                <el-button type="primary">导入</el-button>
            </template>

        </el-upload>
        <el-button type="success">导出</el-button>
    </div>
    <div id="luckysheet" class="luckysheet-container"></div>
</template>

<script setup lang="ts">
import type { UploadFile } from 'element-plus';
import { onMounted, ref } from 'vue';

declare const luckysheet: any;
declare const LuckyExcel: any;
const uploadRef = ref()
const dataSheet = ref(
    [
        {
            name: 'Sheet1', // 第一个工作表名称
            celldata: [], // 单元格初始数据（空表可留空）
            row: 36, // 行数
            column: 18 // 列数
        }
    ]
)

function save() {
    console.info(LuckyExcel.transformExcelToLucky)
    const { data } = luckysheet.toJson()
    localStorage.setItem('luckysheet-data', JSON.stringify(data))
}
function handleImport(rawFile: UploadFile) {
    const formData = new FormData();
    formData.append('file', rawFile.raw!);
    formData.append('name', rawFile.name);
    LuckyExcel.transformExcelToLucky(rawFile.raw, function (exportJson: any, luckysheetfile: any) {
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            alert("Failed to read the content of the excel file, currently does not support xls files!");
            return;
        }
        luckysheet.destroy();
        luckysheet.create({
            container: 'luckysheet', //luckysheet is the container id
            showinfobar: false,
            data: exportJson.sheets,
            title: exportJson.info.name,
            userInfo: exportJson.info.name.creator
        });
    });
    // uploadRef.value!.submit()
}


onMounted(() => {
    if (localStorage.getItem('luckysheet-data')) {
        dataSheet.value = JSON.parse(localStorage.getItem('luckysheet-data') as string)
    }
    luckysheet.create({
        container: 'luckysheet', // 容器 ID（与模板中一致）
        title: '测试表', // 表格标题
        lang: 'zh', // 语言（默认中文）
        allowEdit: true, // 是否允许编辑
        // 可选：初始化表格数据（参考文档「整体结构」的 luckysheetfile 格式）
        data: dataSheet.value
    });
});
</script>

<style scoped>
/* 容器必须设置宽高，否则表格会塌陷 */
.luckysheet-container {
    width: 100%;
    height: 800px;
    /* 可根据需求调整，建议不小于 600px */
    margin: 0;
    padding: 0;
}

.flex {
    display: flex;
    justify-content: end;
    gap: 20px;
    margin-bottom: 20px;
}
</style>